#include "protectedmain.h"
#include <vector>
#include <iostream>
#include <sstream>
#include <span>
static_assert(__cplusplus >= 201703L, "requires c++17 for std::string_view");

void handleHelp();
void handleVersion();

int protectedMain(int argc, char** argv) noexcept(false)
{
    auto endl = true;
#if (__cplusplus > 201703L)
    auto args = std::span(argv, argc);
#else
    std::vector<std::string_view> args;
    for (int i = 0; i < argc; ++i)
    {
        args.emplace_back(argv[i]);
    }
#endif
    std::stringstream ss;
    for (int i = 0, num = 0; i < argc; ++i)
    {
        std::string_view span_arg = args[i];
        if (span_arg == "-n")
        {
            endl = false;
            continue;
        }
        if (span_arg == "--help")
        {
            handleHelp();
        }
        if (span_arg == "--version")
        {
            handleVersion();
        }
        if (num++ > 0)
        {
            ss << " ";
        }
        ss << span_arg.data();
    }
    std::cout << ss.str();
    if (endl)
    {
        std::cout << '\n';
    }
    return EXIT_SUCCESS;
}

void handleHelp()
{
    std::cout << "Usage: echo [SHORT-OPTION]... [STRING]...\n"
              << " or: echo LONG-OPTION\n"
              << "Echo the STRING(s) to standard output.\n"
              << "\n"
              << " -n do not output the trailing newline\n"
              << " --help display this help and exit\n"
              << " --version output version information and exit\n";

    ::exit(EXIT_SUCCESS);
}

void handleVersion()
{
    std::cout << "echo (example) 1.0\n"
              << "Copyleft (C)\n"
              << "\n"
              << "Written by WB.\n";

    ::exit(EXIT_SUCCESS);
}